package xiaoa.java.netty;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 资源
 * @author xiaoa
 * @date 2017年7月25日 下午9:04:10
 * @version V1.0
 *
 */
public class Result {

	
	// 操作步骤次数
    private final int downCount = 3;
	
	// 锁
	private CountDownLatch  returnCount = new CountDownLatch(downCount);;
	

	private  int useCount = 0;

	/**
	 * Channel 是否已关闭
	 */
	private boolean isComplete ;
	
	/**
	 * 完成锁
	 */
	private Object  lock = "";

	// 请求是否成功
	private boolean succ = true;

	
	// 错误信息
	private Throwable  exception = null;

	/**
	 * 等待资源
	 * @Title: waitResult
	 * @param timeout
	 * @author xiaoa
	 * @throws InterruptedException 
	 */
	public void waitResult(long timeout) throws InterruptedException {
		
		if (timeout > 0){
			returnCount.await(timeout, TimeUnit.MILLISECONDS);
		}else {
			returnCount.await();
		}
		
	}
	
	
	/**
	 * 完成连接
	 * @Title: completeHandler
	 * @author xiaoa
	 */
	public void completeConnect(){
		completeResut();
	}
	
	
	/**
	 * 完成填充handler
	 * @Title: completeHandler
	 * @author xiaoa
	 */
	public void completeHandler(){
		completeResut();
	}
	
	
	/**
	 * 完成填充body
	 * @Title: completeBody
	 * @author xiaoa
	 */
	public void completeBody(){
		completeResut();
	}
	
	
	/**
	 * 返回结果
	 * @Title: returnResut
	 * @author xiaoa
	 */
	private void completeResut(){
		
		if (returnCount == null){
			throw new RuntimeException(" no wait ");
		}

		synchronized (lock){
			// 释放锁
			returnCount.getCount();
			returnCount.countDown();
			useCount ++;
			
			// 如果相等， 代表已经完成
			if (useCount == downCount){
				isComplete = true;
			}

		}
	}


	/**
	 *异常状态关闭
	 * @param exceptionClose
     */
	public void exceptionClose(Throwable  exce){

		this.exception = exce;
		// 设置为失败
		succ = false;
		int c = downCount - useCount;
		for (int i = 1 ; i <= c ; i ++ ){
			completeResut();
		}

	}


	
	/**
	 * 是否未使用
	 * @Title: isVirgin
	 * @return
	 * @author xiaoa
	 */
	public boolean isNotUsed(){
		return useCount == 0;
	}
	
	public boolean isSucc() {
		return succ;
	}


	public Throwable getException() {
		return exception;
	}


	public boolean isComplete() {
		return isComplete;
	}

	


	
	
	
	
	
}
